import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus_seven/constants/index.dart';
import 'package:flutter_enjoy_plus_seven/utils/toast.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  // 当前定位地址
  String _address = '';
  final Dio _dio = Dio();

  // 获取定位权限
  _getLocationPermission() async {
    try {
      // 获取定位权限
      final status = await Permission.location.request();
      // 判断权限
      if (status.isGranted) {
        // 权限已授予
        PromptAction.showSuccess('定位权限已授予');
      } else if (status.isDenied) {
        // 权限已拒绝
        PromptAction.showError('定位权限已拒绝');
      }
    } catch (e) {
      PromptAction.showError(e.toString());
    }
  }

  initGDDio() {
    _dio.options
      ..baseUrl = GlobalVariable.GD_BASE_URL
      ..connectTimeout = const Duration(seconds: 10)
      ..receiveTimeout = const Duration(seconds: 10);
  }

  // 高德地图逆地址解析
  _getReverseGeocode() async {
    // 高德地图的逆地址解析 API
    final res = await _dio.get(HTTP_PATH.GD_REGEO, queryParameters: {
      'key': GlobalVariable.GD_KEY, // 高德地图key
      'location': '116.343367,40.060294', // 经纬度
    });
    // print(res.data); // regeocode.formatted_address
    if (res.data['status'] == '1') {
      setState(() {
        _address = res.data['regeocode']['formatted_address'];
      });
    } else {
      PromptAction.showError('逆地址解析失败');
    }
  }

  // 高德地图周边地址（搜索）
  _getAround() async {
    final res = await _dio.get(HTTP_PATH.GD_AROUND, queryParameters: {
      'key': GlobalVariable.GD_KEY, // 高德地图key
      "location": '116.343367,40.060294',
      "keywords": "住宅小区",
      "radius": 500, // 搜索半径
      "offset": 10 // 就查10条
    });
    print(res.data);
  }

  @override
  void initState() {
    // 初始化高德地图dio
    initGDDio();
    // 获取定位权限
    _getLocationPermission();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const Row(
            children: [
              Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(_address)),
                GestureDetector(
                  onTap: () {
                    _getReverseGeocode();
                    _getAround();
                  },
                  child: const Row(
                    children: [
                      Icon(Icons.location_searching_outlined,
                          color: Colors.blue),
                      SizedBox(width: 2),
                      Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: [
              Container(
                color: Colors.white,
                padding: const EdgeInsets.all(10),
                child: const Row(
                  children: [
                    Expanded(child: Text('北京市昌平区政府街19号')),
                    Row(
                      children: [
                        Icon(Icons.arrow_forward_ios,
                            size: 16, color: Colors.black),
                      ],
                    )
                  ],
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}
